<?php

namespace app\admin\model\yungift;


use addons\yungift\model\Config;
use think\Exception;

/**
 * 成员
 */
class Member extends \addons\yungift\model\Member
{
    // 自定义初始化
    protected static function init()
    {
        // 在保存数据前
        Member::event('before_write', function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario) {
                $loginMethods = Config::getGroupAttribute(Config::GROUP_BASE, 'login_methods');
                if ($code = $record['code'] ?? null) {
                    $record['code'] = md5($code);
                    $record['init_code'] = $code;
                    if (strpos($loginMethods, 'name_code') !== false) {
                        $memberIds = Member::where(['name' => $record['name'], 'code' => $record['code']])
                            ->column('id');
                        if ($memberIds && (empty($record['id']) || array_diff($memberIds, [$record['id']]))) {
                            throw new Exception('姓名和登录码在系统已存在，请换一个登录码试试');
                        }
                    }
                } else {
                    unset($record['code']);
                }
                if ($phone = $record['phone'] ?? null) {
                    if (strpos($loginMethods, 'phone_captcha') !== false
                        || strpos($loginMethods, 'wechat_phone') !== false) {
                        $memberIds = Member::where(['phone' => $phone])->column('id');
                        if ($memberIds && (empty($record['id']) || array_diff($memberIds, [$record['id']]))) {
                            throw new Exception('手机号在系统已存在，请换一个手机号试试');
                        }
                    }
                }
            }

            return true;
        });
    }
}
